package top.zhaoyuliu.logbook.client.filter;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import top.zhaoyuliu.logbook.client.builder.ParameterLbBuilder;
import top.zhaoyuliu.logbook.client.constant.Const;
import top.zhaoyuliu.logbook.client.link.LinkThreadLocal;
import top.zhaoyuliu.logbook.client.queue.LbQueue;
import top.zhaoyuliu.logbook.client.utils.AppUtil;

/**
 * Copyright © 2021 Arain. All rights reserved.
 *
 * @Title: LbFilter.java
 * @Prject: logbook-client
 * @Package: top.zhaoyuliu.logbook.client.filter
 * @Description: <功能详细描述>
 * @author: Arain
 * @date: 2021年1月22日 下午10:11:21
 * @version: V1.0
 */
@WebFilter(filterName = "LbFilter", urlPatterns = { "/*" })
@Slf4j
public class LbFilter implements Filter {

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		ServletRequest servlet = new RequestWrapper((HttpServletRequest) servletRequest);
		HttpServletRequest request = (HttpServletRequest) servlet;
		try {
			String trackId = request.getHeader(Const.TRACK);
			if (StrUtil.isBlank(trackId)) {
				trackId = UUID.randomUUID().toString();
			}
			String json = "";
			if (isJson(request)) {
				json = new RequestWrapper(request).getBodyString();
			} else {
				json = JSONUtil.toJsonStr(request.getParameterMap());
			}
			LinkThreadLocal.traceID.set(trackId);
			ParameterLbBuilder parameterLbBuilder = new ParameterLbBuilder(request.getRequestURL().toString(),
					request.getMethod(), AppUtil.getIpAddr(request), json);
			parameterLbBuilder.setTrackId(trackId);
			LbQueue.pushParaQueue(JSONUtil.toJsonStr(parameterLbBuilder));
		} catch (Exception e) {
			log.warn("请求日志采集失败");
		}
		chain.doFilter(servlet, response);
	}

	public static String ReadAsChars(HttpServletRequest request) {

		BufferedReader br = null;
		StringBuilder sb = new StringBuilder("");
		try {
			br = request.getReader();
			String str;
			while ((str = br.readLine()) != null) {
				sb.append(str);
			}
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}

	private boolean isJson(HttpServletRequest request) {
		if (request.getContentType() != null) {
			return request.getContentType().equals("application/json")
					|| request.getContentType().equals("application/json;charset=UTF-8");
		}
		return false;
	}
}
